package klimuts.periodicals.admin;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

import klimuts.periodicals.catalog.Periodical;
import klimuts.periodicals.user.User;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

/**
 * Contains all information about an order placed in database  
 * @author Siarhei Klimuts
 */
@Entity
@Table(name="carts")
public class Order{
	private long id;
	private User owner;
	private float price;
	private Date date;
	private byte status;
	private List<Periodical> periodicals=new LinkedList<Periodical>();
	
	public Order() {}
	
	public Order(User owner, float price, Date date, byte status) {
		super();
		setOwner(owner);
		setPrice(price);
		setDate(date);
		setStatus(status);
	}
	
	public String toString() {
		return "id:"+id+", date:"+date;
	}
	
	/**
	 * Return the number of days that have passed from order date
	 * @return <code>int</code> value of passed days
	 */
	@Transient
	public int getDays() {
		return (int)((new Date().getTime()-date.getTime())/86400000);
	}
	
	/**
	 * Used when need text output of status value
	 * @return Return {@link String} key in *.properties file for current status value. 
	 */ 
	@Transient
	public String getStatusText() {
		return "order.status."+status;
	}

	@Id
	@GeneratedValue
	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}
	
	@OneToOne
	@JoinColumn(name="owner")
	public User getOwner() {
		return owner;
	}

	public void setOwner(User owner) {
		this.owner = owner;
	}

	public float getPrice() {
		return price;
	}

	public void setPrice(float price) {
		this.price = price;
	}
	
	@Temporal(value=TemporalType.DATE)
	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}
	
	public byte getStatus() {
		return status;
	}

	public void setStatus(byte status) {
		this.status = status;
	}

	@ManyToMany()
	@Fetch(FetchMode.JOIN)
	@JoinTable(name = "orders", joinColumns =  @JoinColumn(name="cart"), inverseJoinColumns =  @JoinColumn(name="periodical"))
	public List<Periodical> getPeriodicals() {
		return periodicals;
	}

	public void setPeriodicals(List<Periodical> periodicals) {
		this.periodicals = periodicals;
	}

}
